package com.itheima.consumer.listener;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.consumer.pojo.MessageInfo;
import com.itheima.consumer.service.ConsumerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Sink;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

@Component
@EnableBinding(Sink.class)
public class Reciver {

    @Autowired
    private ConsumerService consumerService;

    @StreamListener(Sink.INPUT)
    public void listener(Message message) throws JsonProcessingException {
        String messages = (String)message.getPayload();

        ObjectMapper objectMapper = new ObjectMapper();
        MessageInfo messageInfo = objectMapper.readValue(messages, MessageInfo.class);
        System.out.println(messageInfo);
        consumerService.add(messageInfo);
    }
}
